#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : chansimulation
# @Time    : 2020/9/12 16:14
# @Author  : wp
# @File    : ChanLogMaker.py
# @Software: PyCharm

"""
调用链日志生成器
"""
import logging
import logging.handlers
import os
import time
import random
from faker import Faker
from utils import dtutils, logutils
from config.config import SysLogConfig,SysConfig

locallogger = logutils.getlogger(__file__ + "_local")


# 获取日志生成器
def getLogger():
    # 日志模块设置--文件日志
    # 第一步，创建一个logger
    logger = logging.getLogger(__file__)
    logger.setLevel(SysLogConfig.gloableloglevel)  # Log等级总开关
    # 第二步，创建一个handler，用于写入日志文件
    rq = dtutils.nowdt2str()
    root_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir))
    # print('*'*50)
    # print("root_dir="+root_dir)
    log_path = os.path.join(root_dir, 'output')
    # 如果不存在定义的日志目录就创建一个
    if not os.path.isdir(log_path):
        os.mkdir(log_path)
    # 获取脚本名称，并以脚本名称作为日志名
    logfile = os.path.join(log_path, os.path.basename('chansimulation_' + rq + '.log'))
    # print('logfile='+logfile)
    # 添加循环写日志的handler
    fh = logging.handlers.RotatingFileHandler(logfile, mode='a', encoding='utf-8', maxBytes=SysConfig.maxBytes, backupCount=SysConfig.backupCount)
    # 文件日志级别
    fh.setLevel(SysLogConfig.fileloglevel)

    # 第三步，定义handler的输出格式

    formatter = logging.Formatter("%(message)s")
    fh.setFormatter(formatter)
    # 第四步，将logger添加到handler里面
    logger.addHandler(fh)

    return logger


def mkAopLog(chandict=None):
    if not chandict:
        # locallogger.error("chandict 传入错误！")
        raise ValueError("chandict 传入错误！")
    if not isinstance(chandict, dict):
        locallogger.error("chandict 类型错误！")
        raise ValueError("chandict 类型错误！")

    logger = getLogger();
    locallogger.info("test")

    f = Faker(locale='zh_CN')

    """
    [日志输出时间戳][线程名][日志级别][微服务托管信息][微服务IP及端口][微服务名称][操作用户][方法URL]
    [业务含义][方法耗时][处理开始时间戳][客户端IP][全局ID][父ID][本地ID]
    """
    logtmplet = "[{timestamp}][{threadname}][{level}][{hostname_ip}][{ip_port}][{servicecode}][{userid}][{url}][{yw}][{cost}][{starttime}][{client_ip}][{globaletraceid}][{fathertraceid}][{localtraceid}][{msg}]"

    fmtmap = {
        'timestamp': dtutils.nowdt2str1(),
        'threadname': '',
        'level': 'info',
        'hostname_ip': '',
        'ip_port': '',
        'servicecode': '',
        'userid': '',
        'url': '',
        'yw': '',
        'cost': '',
        'starttime': '',
        'client_ip': '',
        'globaletraceid': '',
        'fathertraceid': '',
        'localtraceid': '',
        'msg': ''
    }

    # for i in range(100):
    while True:
        # for chankey, chanval in chandict.items():
        chankey=random.choice(list(chandict.keys()))
        chanval = chandict[chankey]
        # logger.info('=====================================================')
        gloabletraceid = f.sha1()
        fathertraceid = '0'
        timestamp = dtutils.nowdt2str1()
        locallogger.info("timestamp={} chankey={}".format(timestamp, chankey))
        for svc in chanval:
            localtraceid = f.sha1()
            fmtmap['threadname'] = 'service' + svc['servicecode']
            fmtmap['hostname_ip'] = '{}-{}'.format(svc['servicecode'], f.uuid4())
            fmtmap['ip_port'] = '192.168.{}.{}:{}'.format(svc['x'], svc['y'], svc['x'] * 10 + svc['y'],)
            fmtmap['servicecode'] = svc['servicecode']
            fmtmap['userid'] = '{:0>6d}'.format(f.random_int())
            fmtmap['url'] = 'http://192.168.{}.{}:{}/{}'.format(svc['x'], svc['y'], svc['x'] * 10 + svc['y'],svc['servicecode'])
            fmtmap['cost'] = f.random_int()
            fmtmap['starttime'] = dtutils.nowdt2str1()
            fmtmap['client_ip'] = f.ipv4()
            fmtmap['globaletraceid'] = gloabletraceid
            fmtmap['fathertraceid'] = fathertraceid
            fmtmap['localtraceid'] = localtraceid
            fmtmap['msg'] = f.address()
            fathertraceid = localtraceid
            logger.info(logtmplet.format_map(fmtmap))
            time.sleep(SysConfig.dtime)


if __name__ == '__main__':
    mkAopLog()
